<div id="printArea">
  <h1>这是要打印的内容</h1>
  <p>只打印这部分内容。</p>
</div>

<button onclick="printDiv('printArea')">打印指定区域</button>

<script>
  function printDiv(divId) {
    var content = document.getElementById(divId).innerHTML
    var printWindow = window.open('', '', '')
    printWindow.document.write('<html><head><title> </title>')
    printWindow.document.write('</head><body >')
    printWindow.document.write(content)
    printWindow.document.write('</body></html>')
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
  }
</script>
